package cn.it.shop.service.impl.flow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.it.shop.model.flow.FlowParameter;
import cn.it.shop.service.flow.FlowParameterService;
import cn.it.shop.service.impl.BaseServiceImpl;
import cn.it.shop.util.GlobalConstants;
import cn.it.shop.util.HttpUtils;
import cn.it.shop.wechat.model.customermessage.ArticleCustomer;
import cn.it.shop.wechat.model.customermessage.News;
import cn.it.shop.wechat.model.customermessage.NewsCustomerMessage;
import net.sf.json.JSONObject;

/***
 * 流程图文实体service实现
 * @author fangyangsheng
 *
 */
@Service("flowParameterService")
public class FlowParameterServiceImpl extends BaseServiceImpl<FlowParameter> implements FlowParameterService{
	
	
	/**
	 * 将FlowParameter解析图文json包发送
	 * @param flowParameter 流程图文实体
	 * @param flowReplyId 流程主体id
	 * @param openid 粉丝id
	 * @param sortnumInt 记录当前步骤,第一次默认为0
	 */
	@Override
	public String sendFlowMessage(FlowParameter flowParameter,long flowReplyId,String openid,int sortnumInt) {
		
		//拼接点击详情页面的url
		String link = flowParameter.getLink();
		//请求参数
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);//粉丝id
		params.put("sortnum",String.valueOf(sortnumInt));//当前步骤
		params.put("flowReplyId", String.valueOf(flowReplyId));//流程主体id
		//拼接url的方法
		String url = HttpUtils.buildUrl(link, params);
		
		NewsCustomerMessage newsCustomerMessage = new NewsCustomerMessage();
    	newsCustomerMessage.setMsgtype("news");
    	newsCustomerMessage.setTouser(openid);
    	//设置图文集合实体,流程只需要一个图文
    	List<ArticleCustomer> articles = new ArrayList<ArticleCustomer>();
    	articles.add(new ArticleCustomer(flowParameter.getTitle(),flowParameter.getDescription(),url,flowParameter.getPicUrl()));
    	News news = new News();
    	news.setArticles(articles);
    	newsCustomerMessage.setNews(news);
    	JSONObject jsonMessage = JSONObject.fromObject(newsCustomerMessage);
    	//获取access_token
    	//从全局变量工具类中取出access_token
		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
		//从全局变量工具类中取出获取所有用户openid的url
		String sendMessage = GlobalConstants.getInterfaceUrl("sendMessage");
		sendMessage += accessToken;
		//发送
		String result = "";//存储结果
		try {
			 result = HttpUtils.sendPostBuffer(sendMessage,jsonMessage.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	

}
